import 'dart:developer';
import 'package:kmxy_base/network/net.dart';
import 'package:kmxy_base/util/sp_util.dart';
import 'package:shared_preferences/shared_preferences.dart';

class DictionaryUtil {
  static final DictionaryUtil i = DictionaryUtil._internal();

  ///工厂构造函数
  factory DictionaryUtil() => i;

  ///构造函数私有化，防止被误创建
  DictionaryUtil._internal();

  init({bool isLog = false}) async {
    Set<String> keys = await SpUtil.getKeys();
    SharedPreferences sp = await SharedPreferences.getInstance();
    for (String key in keys) {
      if (key.contains('dictionary')) {
        await sp.remove(key);
      }
    }
  }

  printLog(String text) {
    log(text);
  }

  Future<List> _netList(String dictKey,
      {String? url, Map<String, dynamic>? queryParameters}) async {
    List tempList = [];
    try {
      var respone = await Net.dio.get(url ?? '/blade-system/dict-biz/dictionary',
          queryParameters: queryParameters ?? {'code': dictKey});
      dynamic data = await respone.data;
      if (data['code'] != 200) {
        printLog(data['msg'].toString());
        return [];
      }
      tempList = data['data'];
      printLog(tempList.toString());
    } catch (e) {
      printLog({'code': 999, 'msg': e.toString()}.toString());
      return [];
    }
    SpUtil.setList('dictionary_$dictKey', tempList);
    return tempList;
  }

  /// 获取字典数据列表
  Future<List> getDictList(String dictKey,
      {String? url, Map<String, dynamic>? queryParameters}) async {
    List? data = await SpUtil.getList('dictionary_$dictKey');
    if (data == null || data.isEmpty) {
      data =
          await _netList(dictKey, url: url, queryParameters: queryParameters);
    }
    return data;
  }

  /// key获取字典value
  String getDictValue(String? dictKey, List dictionaryList) {
    if (dictKey == null) {
      return '';
    }
    for (Map item in dictionaryList) {
      if (dictKey == item['dictKey']) {
        return item['dictValue'];
      }
    }
    return '';
  }

  Future<Map> getKeyMap(List dictKeyList) async {
    Map tempDictionaryMap = {};
    try {
      var respone = await Net.dio
          .get('/blade-system/dict-biz/dictionary-map', queryParameters: {
        'codes': dictKeyList
            .toString()
            .replaceAll('[', '')
            .replaceAll(']', '')
            .replaceAll(', ', ',')
      });
      dynamic data = await respone.data;
      if (data['code'] != 200) {
        printLog(data['msg'].toString());
        return tempDictionaryMap;
      }
      tempDictionaryMap.addAll(data['data']);
      printLog(tempDictionaryMap.toString());
    } catch (e) {
      printLog({'code': 999, 'msg': e.toString()}.toString());
    }
    return tempDictionaryMap;
  }
}
